package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Manage;
import com.joint.core.service.ManageService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxManageAction extends BaseFlowAction {

    @Resource
    private ManageService manageService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private ReadersService readersService;
    @Resource
    private RemindService remindService;

    private Manage manage;
    private int recruitNum;
    private String sex;
    private String age;
    private String edu;
    private String profession;
    private String others;
    private String experience;
    private String createName;
    private Users loginUser;
    private String chargeUsersId;
    private String departId;
    private String postId;
    private int ifCentralStaff;
    private String applyUserName;
    private String applyDate;
    private String applyUserId;
    private String chargeUsers;
    private String departName;
    private String postName;
    private String chargeUsersName;

    /**
     * 下一步审批人的Name的集合，用逗号分隔
     */
    private String nextStepApproversName;

    /**
     * 下一步审批人的id的集合，用逗号分隔
     */
    private String nextStepApproversId;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "manage";
    }

    public String listfordialog(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        pager=manageService.findByPagerAndProcessState(pager, user, "manage", FlowEnum.ProcessState.Finished, params);
        List<Manage> mList;
        if (pager.getTotalCount() > 0){
            mList = (List<Manage>) pager.getList();
        }else{
            mList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Manage manage:mList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",manage.getId());
            rMap.put("name",manage.getName());
            rMap.put("create",manage.getCreater().getName());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //  LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=manageService.findByPagerAndLimit(false, "manage", pager, params);
            }else if(viewtype.equals("2")){
                //招聘中
                params.put("result","0");
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=manageService.findByPagerAndFinish("manage", pager, params);
            }else if(viewtype.equals("3")){
                //招聘完成
                params.put("result","1");
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=manageService.findByPagerAndFinish("manage", pager, params);
            }else if(viewtype.equals("4")){
                //已退回
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Backed});
                pager=manageService.findByPagerAndBack(pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=manageService.findByPagerAndLimit(false, "manage", pager, params);
        }

        List<Manage> mList;
        if (pager.getTotalCount() > 0){
            mList = (List<Manage>) pager.getList();
        }else{
            mList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Manage m:mList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",m.getId());
            rMap.put("creater",m.getCreater()==null?"":m.getCreater().getName());
            rMap.put("recruitNum",m.getRecruitNum());
            rMap.put("post",m.getPost()==null?"":m.getPost().getName());
            rMap.put("department",m.getRecruitDepart()==null?"":m.getRecruitDepart().getName());
            rMap.put("createDate",DataUtil.DateToString(m.getCreateDate(),"yyyy-MM-dd"));
            String state=m.getProcessState().name();
            if(StringUtils.isNotEmpty(state)) {
                if (state.equals("Finished")) {
                    rMap.put("state", "招聘中");
                } else if (state.equals("Running")) {
                    rMap.put("state", m.getProcessState().value());
                } else if (state.equals("Backed")) {
                    rMap.put("state", m.getProcessState().value());
                }
                String result = m.getResult();
                if (result != null && result.equals("1")) {
                    rMap.put("state", "招聘完成");

                }
                JSONObject o = JSONObject.fromObject(rMap);
                dataRows.add(o);
            }
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 详情
     * @return
     */
    public String read(){

        loginUser=usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            manage = manageService.get(keyId);
            //sex=manage.getSex().value();
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            applyDate=DataUtil.DateToString(manage.getCreateDate(),"yyyy-MM-dd");

        }

        return "read";
    }

    /**
     * 新建／编辑
     * @return
     */
    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            manage= manageService.get(keyId);
            applyUserName=manage.getCreater().getName();
            applyDate= DataUtil.DateToString(manage.getCreateDate(),"yyyy-MM-dd");

        } else {
            applyUserName=usersService.getLoginInfo().getName();
            applyDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }

        return "input";
    }

    private void setData(){

        Set<Users> usersSet= Sets.newHashSet();
        if(StringUtils.isNotEmpty(keyId)){
            manage = manageService.get(keyId);
        }else{
            manage = new Manage();
            manage.setCreater(usersService.getLoginInfo());
        }

        if(StringUtils.isNotEmpty(chargeUsersId)){
            for(String id:chargeUsersId.split(",")){
                usersSet.add(usersService.get(id.trim()));
            }
        }
        if(StringUtils.isNotEmpty(departId)){
            manage.setRecruitDepart(departmentService.get(departId));
        }
        if(StringUtils.isNotEmpty(postId)){
            manage.setPost(postService.get(postId));
        }
        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    manage.setIfCentralStaff(1);
                }
            }

        }
        manage.setChargeUsers(usersSet);
        manage.setRecruitNum(recruitNum);
        manage.setSex(BaseEnum.SexEnum.valueOf(sex));
        manage.setAge(age);
        manage.setEdu(edu);
        manage.setResult("0");
        manage.setProfession(profession);
        manage.setExperience(experience);
        manage.setOthers(others);
        manage.setNextStepApproversId(nextStepApproversId);
        manage.setNextStepApproversName(nextStepApproversName);
        manage.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 通过
     */
    public String update(){
        //setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                Manage entity =manageService.get(keyId);
                entity.setResult("1");
                manageService.update(entity);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                manageService.update(manage);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                manageService.save(manage, "manage", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        ArrayList<String> list = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
            list.add(uid.trim());
        }

        Set<Users> usersSet= Sets.newHashSet();
        Set<Users> usersList = manage.getChargeUsers();
        for(Users users:usersList){
            usersSet.add(users);
            //LogUtil.info("++++"+usersSet);
        }
        /*for(String id:chargeUsersId.split(",")){
            usersSet.add(usersService.get(id.trim()));
        }*/

        var2.put("approvers", list);    // 会签人Ids

        var2.put("ifCentralStaff", manage.getIfCentralStaff());

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                manageService.approve(manage, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId=manageService.commit(manage, "manage", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        //增加归档后读者
        for(Users users:usersSet){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("manage");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }

        for(Users users:usersSet){
            Remind remind = new Remind();
            remind.setUsers(users);
            remind.setBussinessKey("manage");
            remind.setKeyId(keyId);
            remind.setContent("面试负责人");
            remindService.save(remind);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批1
     * @return
     */
    public String approve1(){
        manage = manageService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        if(manage.getIfCentralStaff()==1){
            LogUtil.info("ifCentralStaff"+manage.getIfCentralStaff());
            var1.put("numStatus",3);
        }else{
            var1.put("numStatus", 2);
        }
        var1.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                manageService.approve(manage, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 审批2
     * @return
     */
    public String approve2() {

        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        manage = manageService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        try {
            manageService.approve(manage, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 会签
     * @return
     */
    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        manage = manageService.get(keyId);
         /*Task task=workflowService.getCurrentTask(keyId, usersService.getLoginInfo());
         Map<String, Object> var2 = new HashMap<String, Object>();

        int multComplete = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfCompletedInstances");
        int nrOfInstances = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfInstances");
        LogUtil.info("multComplete:"+multComplete);
        LogUtil.info("nrOfInstances:"+nrOfInstances);

        if((double)multComplete/nrOfInstances>=1){
            var2.put("numStatus", 4);
            manageService.approve(manage, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);


        } else {
            var2.put("numStatus", 3);
        }*/

        Map<String, Object> var2 = new HashMap<String, Object>();
        // var2.put("curDutyId", curDutyId);
        try {
            manageService.approve(manage, FlowEnum.ProcessState.Running, var2, curDutyId, comment);

            Task overtask = workflowService.getCurrentTask(keyId);
            if(overtask==null){
                Manage man=manageService.get(keyId);
                man.setProcessState(FlowEnum.ProcessState.Finished);
                manageService.update(man);

            }else {

                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){

                runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 4);
                }
        }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            manage = manageService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("manage");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            if(StringUtils.isEmpty(comment)) comment="";
            manageService.reject(manage, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            manage = manageService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("manage");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            manageService.deny(manage, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    public Manage getManage() {
        return manage;
    }

    public void setManage(Manage manage) {
        this.manage = manage;
    }

    public int getRecruitNum() {
        return recruitNum;
    }

    public void setRecruitNum(int recruitNum) {
        this.recruitNum = recruitNum;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getChargeUsersId() {
        return chargeUsersId;
    }

    public void setChargeUsersId(String chargeUsersId) {
        this.chargeUsersId = chargeUsersId;
    }

    public String getNextStepApproversName() {
        return nextStepApproversName;
    }

    public void setNextStepApproversName(String nextStepApproversName) {
        this.nextStepApproversName = nextStepApproversName;
    }

    public String getNextStepApproversId() {
        return nextStepApproversId;
    }

    public void setNextStepApproversId(String nextStepApproversId) {
        this.nextStepApproversId = nextStepApproversId;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getEdu() {
        return edu;
    }

    public void setEdu(String edu) {
        this.edu = edu;
    }

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

    public String getExperience() {
        return experience;
    }

    public void setExperience(String experience) {
        this.experience = experience;
    }
    public String getCreateName() {
        return createName;
    }

    public void setCreateName(String createName) {
        this.createName = createName;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public String getApplyUserName() {
        return applyUserName;
    }

    public void setApplyUserName(String applyUserName) {
        this.applyUserName = applyUserName;
    }

    public String getApplyDate() {
        return applyDate;
    }

    public void setApplyDate(String applyDate) {
        this.applyDate = applyDate;
    }

    public String getOthers() {
        return others;
    }

    public void setOthers(String others) {
        this.others = others;
    }

    public String getApplyUserId() {
        return applyUserId;
    }

    public void setApplyUserId(String applyUserId) {
        this.applyUserId = applyUserId;
    }

    public String getChargeUsers() {
        return chargeUsers;
    }

    public void setChargeUsers(String chargeUsers) {
        this.chargeUsers = chargeUsers;
    }

    public String getDepartName() {
        return departName;
    }

    public void setDepartName(String departName) {
        this.departName = departName;
    }

    public String getPostName() {
        return postName;
    }

    public void setPostName(String postName) {
        this.postName = postName;
    }

    public String getChargeUsersName() {
        return chargeUsersName;
    }

    public void setChargeUsersName(String chargeUsersName) {
        this.chargeUsersName = chargeUsersName;
    }
}
